package com.jsh.erp.generator;

import com.baomidou.mybatisplus.generator.config.IFileCreate;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.jsh.erp.utils.DocumentUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class FileCreateStrategy implements IFileCreate {
    private boolean createCtr;
    private boolean createServ;

    private Map<String, Document> oldXmlDoc = new HashMap<>();

    public FileCreateStrategy(boolean createCtr, boolean createServ) {
        this.createCtr = createCtr;
        this.createServ = createServ;
    }

    @Override
    public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
        boolean fileExists = new File(filePath).exists();
        switch (fileType) {
            case CONTROLLER:
                return !fileExists && createCtr; //如果文件存在，则不创建
            case SERVICE:
                return !fileExists && createServ; //如果文件存在，则不创建
            case SERVICE_IMPL:
                return !fileExists && createServ; //如果文件存在，则不创建
            case MAPPER:
                return !fileExists; //如果文件不存在，则创建
            case ENTITY: //直接创建覆盖entity
                return true;
            case XML:
                return !fileExists; //如果文件存在，则不创建
//                return handleXMLCreate(fileExists, configBuilder, filePath); //合并XML
            case OTHER:
                return !fileExists; //如果文件存在，则不创建
                /*if(filePath.endsWith(".xml")) {
                    return  handleXMLCreate(fileExists, configBuilder, filePath);
                } else {
                    return !fileExists;
                }*/
        }
        return true;
    }

    public void doMergeXmlFiles() {
        for(Map.Entry<String, Document> entry : oldXmlDoc.entrySet()) {
            doMergeXmlFile(entry.getKey(), entry.getValue());
        }
    }

    private void doMergeXmlFile(String filePath, Document oldDoc) {
        String finallyXML = null;
        try (StringWriter writer = new StringWriter()) {
            Element oldRoot = oldDoc.getDocumentElement();
            Document newDoc = DocumentUtil.parseXml(filePath);
            Map<String, Node> oldNodes = getMapperNodes(oldDoc);
            Map<String, Node> newNodes = getMapperNodes(newDoc);
            for(Map.Entry<String, Node> newNodeEntry : newNodes.entrySet()) {
                if(oldNodes.containsKey(newNodeEntry.getKey())) { //原有的mapper中已经存在，替换
                    Node newNode = oldDoc.importNode(newNodeEntry.getValue(), true);
                    oldRoot.replaceChild(newNode, oldNodes.get(newNodeEntry.getKey()));
                } else { //如果老的中不存在，属于新增的部分
                    oldRoot.appendChild(newNodeEntry.getValue());
                }
            }
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(oldDoc);
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);
            String output = writer.getBuffer().toString(); // .replaceAll("\n|\r", "");
            String[] arr = output.split("\n", 2); // 将字符串分为两部分
            // 处理读取之后 documentType dtd等信息没有的问题
            // 没有找的有效的解决的办法，直接操作字符串来处理
            StringBuilder sb = new StringBuilder(arr[0])
                    .append("\n")
                    .append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">")
                    .append("\n")
                    .append(arr[1]);
            //将String写入文件中
            finallyXML = sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("doMergeXmlFile error,file path:" + filePath, e);
        }
        try(FileOutputStream fos = new FileOutputStream(filePath);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
            BufferedWriter bw = new BufferedWriter(osw)) {
            bw.write(finallyXML);
        } catch (Exception e) {
            System.out.println("--------------------" + filePath + " new XML String ------------------------");
            System.out.println(finallyXML);
            throw new RuntimeException("write to " + filePath + " failed", e);
        }
    }

    private Map<String, Node> getMapperNodes(Document doc) {
        Map<String, Node> map = new LinkedHashMap<>();
        Element root = doc.getDocumentElement();
        NodeList childNodes = root.getChildNodes();
        for(int i=0;i<childNodes.getLength();i++) {
            Node item = childNodes.item(i);
            if(item.getNodeType() == 1) { // node
                map.put(item.getAttributes().getNamedItem("id").toString(), item);
                System.out.println(item.getAttributes().getNamedItem("id"));
            }
        }
        return map;
    }

    private boolean handleXMLCreate(boolean exist, ConfigBuilder configBuilder, String filePath) {
        if(!exist) {
            return true;
        }
        // 记录老的文件内容
        // 等代码生成器工作完成后，再进行合并操作
        try {
            Document doc = DocumentUtil.parseXml(filePath);
            System.out.println(filePath + "==========record old xml string==============================");
            System.out.println(readXmlFile(filePath));
            oldXmlDoc.put(filePath, doc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private String readXmlFile(String filePath) {
        try(FileInputStream fis = new FileInputStream(filePath);
            InputStreamReader isr = new InputStreamReader(fis, "utf-8");
            BufferedReader br = new BufferedReader(isr)){
            StringBuilder sb = new StringBuilder();
            br.lines().forEach(line -> sb.append(line).append("\n"));
            return sb.toString();
        }catch (IOException e) {
            throw new RuntimeException("read " + filePath + " error", e);
        }
    }


}
